// 获取显示屏和按钮
const display = document.getElementById('display');
const buttons = Array.from(document.querySelectorAll('.buttons button'));

// 当前输入的数字或符号
let currentInput = '';
// 上一个输入的数字
let previousInput = '';
// 当前操作符
let operator = null;

// 进行计算的函数
const operate = (a, b, operator) => {
    a = parseFloat(a);
    b = parseFloat(b);

    switch(operator) {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '÷':
            return a / b;
        default:
            return b;
    }
}

// 接下来为每个按钮添加点击事件监听器
buttons.forEach(button => {
    button.addEventListener('click', (e) => {
        const value = e.target.innerText;
        // 清空输入
        if (value === 'C') {
            currentInput = '';
            previousInput = '';
            operator = null;
            display.value = '';
        }
        // 删除一个字符
        else if (value === 'CE') {
            currentInput = currentInput.slice(0, -1);
            display.value = currentInput;
        }
        // 计算结果
        else if (value === '=') {
            if (previousInput && operator && currentInput) {
                currentInput = operate(previousInput, currentInput, operator).toString();
                display.value = currentInput;
                previousInput = '';
                operator = null;
            }
        }
        // 输入运算符
        else if (['+', '-', '*', '÷'].includes(value)) {
            if (currentInput) {
                if (previousInput && operator) {
                    previousInput = operate(previousInput, currentInput, operator).toString();
                }
                else {
                    previousInput = currentInput;
                }
                operator = value === '÷' ? '/' : value; // 将 ÷ 转换为 /
                currentInput = '';
            }
        }
        // 输入数字或者小数点
        else {
            currentInput += value;
            display.value = currentInput;
        }
    })
})

